package com.app.common.utils;

import java.io.UnsupportedEncodingException;

public class StringUtil {
	
	/**
	 * 截取指定长度的字符串,并可在截取字符串后面随意添加任意字符
	 * @param text 要截取的文本字符串
	 * @param length 截取长度(中文即length，英文即length*2)
	 * @param endWith 截取后末尾要加的字符(例如：...)
	 * @author CCR
	 * @return returnStr 截取后的字符串
	 */
	public static String interceptString(String text, int length, String endWith) {
		int textLength = text.length();
		int byteLength = 0;
		StringBuffer returnStr = new StringBuffer();
		for (int i = 0; i < textLength && byteLength < length * 2; i++) {
			String str_i = text.substring(i, i + 1);
			if (str_i.getBytes().length == 1) {// 英文
				byteLength++;
			} else {// 中文
				byteLength += 2;
			}
			returnStr.append(str_i);
		}
		try {
			// getBytes("GBK")每个汉字长2，getBytes("UTF-8")每个汉字长度为3
			if (byteLength < text.getBytes("GBK").length) {
				returnStr.append(endWith);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return returnStr.toString();
	}
	
	/**
	 * object对象转换为String类型
	 * @param ojb 要强转的对象
	 * @return 返回强转后的string(兼容null时为空字符串)
	 */
	public static String parse2String(Object ojb){
		String returenStr = String.valueOf(ojb);
		if (returenStr == null || returenStr.equalsIgnoreCase("null")|| returenStr.equalsIgnoreCase("undefined")){
			return "";
		}else{
			return returenStr.trim();
		}
	}
	
	/**
	 * 判断字符串是否为空
	 * @param Str 要检查的字符串
	 * @return true OR false
	 */
	public static boolean isNotEmpty(String Str){
		
		if (Str == null || Str.equalsIgnoreCase("null")|| Str.equals("") || Str == ""){
			return false;
		}else{
			return true;
		}
	}
	
	
	public static void main(String args[]) {
		System.out.println(StringUtil.interceptString("abcde是hijk", 5, "/////////"));
	}
}
